'use strict';
import React from 'react';
import $ from 'jquery'
import pay from '../img/pay/pay.png'
import {R_header_fixed} from './common/index';
import select from '../img/pay/select.png'
import unselect from '../img/pay/unselect.png'
import record from '../img/pay/record.png'
import gou from '../img/pay/gou.png'
import Popup from './common/popup'
import weixin from '../img/weixin.png'
import alipay from '../img/alipay.png'
import success from '../img/pay/success.png'
import fail from '../img/pay/fail.png'
import {HttpService, Toast} from '../utils'
//import WxServer from '../wx/WxServer'

class Pay extends React.Component {

    constructor() {
        super();
        this.state = {
            type: 1,
            payType:2,
            money: 100,
            deviceInfo: [],
            orders: [],
            isShow: false
        }
        this.config = {
            isSure: true,
            isCancel: false,
            tip: true,
            no: '我知道了',
            content: <div style={{width: "100%"}}><p style={{textAlign: 'center', fontSize: '40px', color: "#ff7f74"}}>
                购买结束</p></div>,
            no_cb: () => {
                let len = window.history.length - localStorage.len + 1;
                window.history.go(-len);
            }
        };
    }

    componentWillMount() {

        this.getDevices();
        this.getPayLogs();

    }
    componentDidMount(){
        var rec = this;
        if (location.href.indexOf("back") > 0) {
            $.ajax({
                url: '/pay/getOrderStatus',
                sync: false,
                data: {
                    token: localStorage.appToken,
                    orderno: localStorage.orderno
                },
                type:'post',
                success: function (res) {
                    if(res.code=="0"){
                        if(res.data.tradestatus==2){
                            rec.config.content= <div className="tipimg"><img  src={success} /><p>支付成功!</p></div>
                        }else if(res.data.tradestatus==3){
                            rec.config.content= <div className="tipimg"><img  src={fail} /><p>支付失败!</p></div>
                        }
                        rec.setState({
                            isShow: true
                        })
                    }else{
                        rec.config.content= <div className="tipimg"><img  src={fail} /><p>res.msg</p></div>
                        rec.setState({
                            isShow: true
                        })
                    }
                },
                error: function () {

                }
            });

        } else {
            localStorage.len = window.history.length;

        }
    }

    async getDevices() {
        const code = await HttpService.query({
            url: '/app/device/getDevices',
            data: {
                token: localStorage.appToken,
                babyid: this.props.params.babyid,
                deviceid: this.props.params.deviceid,
                weixinclient: 'true'
            }
        });
        if (code.code == '10132') {
            this.setState({deviceInfo: code.data})
        }
    }

    async renewalFees(type, money, deviceprice) {
        let rec=this;
        const code = await HttpService.query({
            url: '/app/device/renewalFees',
            data: {
                token: localStorage.appToken,
                babyid: this.props.params.babyid,
                deviceid: this.props.params.deviceid,
                time: type + 'years',
                source: 'ALIPAY_H5',
                fee: deviceprice + ',' + money,
                weixinclient: 'true'
            }
        })
        console.log(code);
        if (code.code == '10134') {
            localStorage.orderno=code.data;
            if(rec.state.payType==1){
                $.ajax({
                    url: '/wxpay/wxmweb/unified_order',
                    type: 'post',
                    data: {
                        token: localStorage.appToken,
                        orderno: code.data,
                        payType:'WEIXIN_H5'
                    },
                    success: function (res) {
                        window.location.href=res.data;
                    },
                    error: function () {

                    }
                });
            }else if(rec.state.payType==2){
                $.ajax({
                    url: '/pay/getPay',
                    type: 'post',
                    data: {
                        token: localStorage.appToken,
                        orderno: code.data,
                        payType: 'ALIPAY_H5',
                        returnurl: location.href.split("#")[0] + `#/pay/${localStorage.babyid}/${localStorage.deviceId}/back`,
                        ordernotype:1
                    },
                    success: function (res) {
                        if (res.code == "0") {
                            document.write(res.data)
                        } else {
                            Toast.toast(res.msg);
                        }
                    },
                    error: function () {

                    }
                });
            }

        } else {
            Toast.toast(code.msg)
        }
    }

    pay(type, money, deviceprice) {
        // if (!/micromessenger/.test(navigator.userAgent.toLowerCase())) {
        //     Toast.toast('请在微信端登录后才可使用支付')
        //     return;
        // }
        this.renewalFees(type, money, deviceprice);
    }

    async getPayLogs() {
        const code = await HttpService.query({
            url: '/app/device/getPayLogs',
            data: {
                token: localStorage.appToken,
                deviceid: this.props.params.deviceid,
                pageindex: '1',
                pagesize: '30',
                weixinclient: 'true'
            }
        });
        if (code.code == '10156') {
            console.log(code);
            this.setState({orders: code.data.orders})
        }
    }

    select(type) {
        this.setState({type: type})
    };

    paySelect(type) {
        this.setState({payType: type})
    };

    render() {
        const {type, deviceInfo, orders,payType,isShow} = this.state;
        const packagefee = deviceInfo[0]
            ? (deviceInfo[0].packagefee).toFixed(2)
            : '';
        const deviceprice = deviceInfo[0] && deviceInfo[0].deviceprice
            ? (deviceInfo[0].deviceprice).toFixed(2)
            : 0;
        const endtime = deviceInfo[0]
            ? deviceInfo[0].endtime
            : '';
        return (
            <div className="app-pay">
                <R_header_fixed left="1" title="缴费"/>
                <Popup config={this.config} blockOrNone={isShow} _flag={isShow}/>
                <div className="app-padding-lr20" style={{paddingBottom:"300px"}}>
                    {deviceInfo.length != 0
                        ? deviceInfo.map((deviceInfo, index) => (
                            <div className="card" key={index}>
                                <div className="step pay-pt-22">
                                    <div className="app-666-font32">{deviceInfo.devicetype == '2'
                                        ? '智能学生证'
                                        : ''}</div>
                                </div>
                                <div className="step app-666-font28 app-padding-tb16 app-line-height-one">
                                    <div className="s-flex1">昵称：{deviceInfo.babyname}</div>
                                    <div className="s-flex1 s-j-end">设备到期时间</div>
                                </div>

                                <div className="step app-666-font28">

                                    <div className="s-flex1" style={{
                                        flex: '2'
                                    }}>手机号：{deviceInfo.telephone}</div>
                                    <div className="s-flex1 app-active-font28 s-j-center">{deviceInfo.endtime}</div>
                                </div>
                                <div className="step app-active-font28 pay-pb-22 pay-pt-16">
                                    {/*<div className="s-flex1">*/}
                                    {/*推广价：{deviceInfo.deviceprice?deviceInfo.deviceprice.toFixed(2):0}*/}
                                    {/*</div>*/}
                                </div>
                                <div className="step pay-height">
                                    <div className="s-flex1">
                                        <div className="app-img">
                                            <img src={gou} className="app-all-img"/>
                                        </div>
                                        <div className="app-666-font30">移动套餐</div>
                                    </div>
                                    <div className="s-flex1 s-j-end app-333-font28">
                                        <div className="app-img" onClick={this.select.bind(this, 1)}>
                                            <img src={type == 1
                                                ? select
                                                : unselect} className="app-all-img"/>
                                        </div>
                                        <div className="app-padding-r24">1年</div>
                                        <div className="app-img s-j-end" onClick={this.select.bind(this, 2)}>
                                            <img src={type == 2
                                                ? select
                                                : unselect} className="app-all-img"/>
                                        </div>
                                        <div>2年</div>
                                    </div>
                                </div>
                                <div className="step app-active-font28">
                                    <div className="s-flex1 pay-pt-22">
                                        价格：{deviceInfo.packagefee.toFixed(2)}/年
                                    </div>
                                </div>
                                <div className="step app-666-font28">
                                    <div className="s-flex1 pay-pb-22 pay-pt-16">
                                        优惠：缴1年送1个月（送缴费当月）；缴2年送3个月（送缴费当月和次2月）。
                                    </div>
                                </div>

                            </div>
                        ))
                        : ''
                    }
                    {orders.length != 0 ? <div className="step" style={{
                        marginBottom: '10px'
                    }}>
                        <div className="s-flex1">
                            <div className="app-img">
                                <img src={record} className="app-all-img"/>
                            </div>
                            <div className="app-666-font24">缴费记录</div>
                        </div>
                    </div> : ''}

                    <div>
                        {orders.length != 0
                            ? orders.map((order, index) => (
                                <div className="card" key={index}>
                                    <div className="step">
                                        <div className="s-flex1 app-333-font28 pay-pt-22">
                                            缴费账号:{order.peopletel}{order.familystatus}</div>
                                    </div>
                                    <div className="step app-666-font24 pay-pt-16 pay-pb-22" style={{
                                        borderBottom: '1px dashed #eee'
                                    }}>
                                        <div className="s-flex1">{order.createtime}</div>
                                        <div className="s-flex1 s-j-end">缴费金额：{order.fee}</div>
                                    </div>
                                    <div className="step app-active-font24">
                                        {/*<div className="s-flex1 pay-height-60">设备到期时间:{endtime}</div>*/}
                                    </div>
                                </div>
                            ))
                            : ''
                        }
                    </div>
                </div>
                <div className="choosePay">
                    {/*<div className="title">请选择支付方式：</div>*/}
                    <ul className="type">
                        {/*<li className="step">*/}
                            {/*<img className="icon" src={weixin}/>*/}
                            {/*<div>微信支付</div>*/}
                            {/*<div className="app-img" onClick={this.paySelect.bind(this, 1)}>*/}
                                {/*<img src={payType == 1*/}
                                    {/*? select*/}
                                    {/*: unselect} className="app-all-img"/>*/}
                            {/*</div>*/}

                        {/*</li>*/}
                        <li className="step">
                            <img className="icon" src={alipay}/>
                            <div>支付宝支付</div>
                            <div className="app-img s-j-end" onClick={this.paySelect.bind(this, 2)}>
                                <img src={payType == 2
                                    ? select
                                    : unselect} className="app-all-img"/>
                            </div>

                        </li>
                    </ul>
                </div>
                {(type * packagefee + parseFloat(deviceprice)).toFixed(2) == '0.00'
                    ? ''
                    : <div className="pay-fixed step">
                        <div className="s-flex1 pay-number app-333-font28">总价:
                            <span
                                className="app-active-font28">{(type * packagefee + parseFloat(deviceprice)).toFixed(2)}</span>
                        </div>
                        <div className="pay" onClick={this.pay.bind(this, type, packagefee, deviceprice)}>结算</div>
                    </div>}
            </div>
        )
    }
}
export default Pay;
